﻿using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;

namespace HsServerHa.Utility.DataHelper
{
    public class DataHelpers
    {
        public string DataTableToJson(DataTable dt)
        {
            return JsonConvert.SerializeObject(dt, Formatting.Indented);
        }

        /// <summary>
        /// DataTable转List<T>
        /// 朱润来
        /// 2023年10月12日09:54:57
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> ConvertToModel<T>(DataTable dt) where T : new()
        {

            List<T> ts = new List<T>();// 定义集合
            Type type = typeof(T); // 获得此模型的类型
            string tempName = "";
            foreach (DataRow dr in dt.Rows)
            {
                T t = new();
                PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
                foreach (PropertyInfo pi in propertys)
                {
                    tempName = pi.Name;
                    if (dt.Columns.Contains(tempName))
                    {
                        if (!pi.CanWrite) continue;
                        object value = dr[tempName];
                        if (value != DBNull.Value)
                        {
                            pi.SetValue(t, value, null);
                        }

                    }
                }
                ts.Add(t);
            }
            return ts;
        }

        /// <summary>
        ///List<T>转DataTable
        ///朱润来
        ///2023年10月12日09:55:02
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collection"></param>
        /// <returns></returns>
        public static DataTable ListToDt<T>(IEnumerable<T> collection)
        {
            var props = typeof(T).GetProperties();
            var dt = new DataTable();
            dt.Columns.AddRange(props.Select(p => new
            DataColumn(p.Name, p.PropertyType)).ToArray());
            if (collection.Count() > 0)
            {
                for (int i = 0; i < collection.Count(); i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in props)
                    {
                        object obj = pi.GetValue(collection.ElementAt(i), null);
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    dt.LoadDataRow(array, true);
                }
            }
            return dt;
        }

        /// <summary>
        /// 删除文件
        /// 朱润来
        /// 2023年10月12日09:54:04
        /// </summary>
        /// <param name="fileDirect">文件地址</param>
        /// <param name="saveDay">保留几天的文件</param>
        public static void DeleteFile(string fileDirect, int saveDay)
        {
            DateTime nowTime = DateTime.Now;
            string[] files = Directory.GetFiles(fileDirect, ".", SearchOption.AllDirectories); //获取该目录下所有文件
            foreach (string file in files)
            {
                FileInfo fileInfo = new FileInfo(file);
                TimeSpan t = nowTime - fileInfo.CreationTime; //当前时间 减去 文件创建时间
                int day = t.Days;
                if (day > saveDay) //保存的时间 ； 单位：天
                {
                    File.Delete(file); //删除超过时间的文件
                }
            }
        }

        /// <summary>
        /// 删除目录
        /// </summary>
        /// <param name="fileDirect">文件地址</param>
        /// <param name="saveDay">保留几天的文件</param>
        public static void DeleteDirectory(string fileDirect, int saveDay)
        {
            DateTime nowTime = DateTime.Now;
            DirectoryInfo root = new DirectoryInfo(fileDirect);
            DirectoryInfo[] dics = root.GetDirectories();//获取文件夹
            FileAttributes attr = File.GetAttributes(fileDirect);

            foreach (DirectoryInfo file in dics)//遍历文件夹
            {
                if (file.EnumerateDirectories().Count() > 0)
                {
                    DeleteDirectory(file.FullName, saveDay);
                }
                TimeSpan t = nowTime - file.LastWriteTime; //当前时间 减去 文件创建时间
                int day = t.Days;
                if (day > saveDay) //保存的时间 ； 单位：天
                {
                    Directory.Delete(file.FullName, true); //删除超过时间的文件夹
                }
            }
            //if (attr == FileAttributes.Directory)//判断是不是文件夹
            //{

            //}
        }

        // 计算文件的MD5指纹
        public static string GetFileHash(string filePath)
        {
            using (var md5 = MD5.Create())
            {
                using (var stream = File.OpenRead(filePath))
                {
                    byte[] hash = md5.ComputeHash(stream);
                    return BitConverter.ToString(hash).Replace("-", "").ToLower();
                }
            }
        }
    }
}
